<route lang="json5" type="page">
{
  layout: "tabbar",
  style: {
    navigationStyle: "custom",
    navigationBarTitleText: "最新资讯",
  },
}
</route>

<template>
  <view class="overflow-hidden news-container">
    <view class="news-bg"></view>
    <view
      class="news-title"
      :style="{
        paddingTop: safeAreaInsets?.top ? safeAreaInsets.top + 'px' : '40px',
        height: safeAreaInsets?.top ? 'auto' : '88rpx',
      }"
      >最新资讯</view
    >
    <view class="news-inner">
      <view>
        <view
          class="news-box mb-20rpx"
          v-for="(item, index) in newsList"
          :key="index"
        >
          <!-- 内容区域改为垂直布局 -->
          <view class="flex flex-col">
            <!-- 上半部分：新闻内容 -->
            <view
              @click="() => goDetailPage(item.id)"
              class="flex justify-between"
            >
              <!-- 这里保持左右布局 -->
              <view class="flex-1 p-20rpx relative">
                <!-- 热门标签 -->
                <!-- <view
                  class="flex absolute left-20rpx top-20rpx"
                  v-if="item.isHot"
                >
                  <image
                    class="w-[91rpx] h-[32rpx]"
                    src="/static/images/top.png"
                    mode="aspectFill"
                  />
                  <image
                    class="h-[32rpx] w-[32rpx] ml-[-28rpx]"
                    src="/static/images/news-fire.png"
                  />
                </view> -->

                <!-- 新闻标题 -->
                <view class="text-#000 text-28rpx ellipsis-2-lines">
                  {{ item.title }}
                </view>

                <!-- 新闻摘要 -->
                <view class="text-#a6a6a6 text-20rpx mt-10rpx ellipsis-2-lines">
                  {{
                    item?.content
                      .replace(/<[^>]+>/g, "") // 去除所有HTML标签
                      .slice(0, 12) + // 截取前12个字符
                    (item?.content.replace(/<[^>]+>/g, "").length > 12
                      ? "..."
                      : "")
                  }}</view
                >

                <!-- 底部信息栏 -->
                <view class="absolute bottom-10rpx left-0 w-100%">
                  <view class="flex justify-between pl-20rpx pr-20rpx">
                    <view class="text-18rpx text-#a6a6a6">{{
                      item.publishTime
                    }}</view>
                  </view>
                </view>
              </view>

              <!-- 新闻配图（保持在右侧） -->
              <image
                class="h-[198rpx] w-[363rpx]"
                :src="item.coverImage?.split(',')[0]"
                mode="aspectFill"
              />
            </view>

            <!-- 下半部分：管理员操作按钮 -->
            <view
              v-if="
                superManagerPermission(userInfo?.role) ||
                managerPermission(userInfo?.role)
              "
              class="admin-actions flex justify-around p-10rpx mt-10rpx border-t-solid border-t-1 border-t-gray-300"
            >
              <button
                @click="handleUnpin(item.id, 'untop')"
                v-if="item.isTop === 1"
                size="mini"
                class="btn-info"
              >
                取消置顶
              </button>
              <button
                class="btn-primary"
                @click="handleUnpin(item.id, 'top')"
                v-else
                size="mini"
              >
                置顶
              </button>

              <button
                class="btn-danger"
                @click="handleDelete(item.id)"
                size="mini"
                type="warn"
              >
                删除
              </button>

              <button
                class="btn-secondary"
                @click="handleToggleStatus(item.id, 'offline')"
                v-if="item.status === 1"
                size="mini"
              >
                下架
              </button>

              <button
                class="btn-success"
                @click="handleToggleStatus(item.id, 'online')"
                v-else
                size="mini"
              >
                上架
              </button>
              <button class="btn-warning" @click="handleEdit(item)" size="mini">
                编辑
              </button>
            </view>
          </view>
        </view>
      </view>
      <view
        style="bottom: 300rpx"
        v-if="
          superManagerPermission(userInfo?.role) ||
          managerPermission(userInfo?.role)
        "
      >
        <uni-fab
          ref="fab"
          direction="horizontal"
          horizontal="right"
          :pattern="{
            buttonColor: '#fff',
            iconColor: '#333',
            selectedColor: '#f0f0f0', // 按下状态颜色
            zIndex: 9999,
          }"
          :style="{ bottom: '550rpx' }"
          @fabClick="openPopup"
        />
      </view>
      <!-- 底部弹出层 -->
      <uni-popup
        ref="popupRef"
        type="bottom"
        :is-mask-click="true"
        :safe-area="false"
      >
        <view class="popup-content">
          <view class="flex-1 flex">
            <image
              class="h-[96rpx] w-[96rpx]"
              :src="userInfo?.avatarUrl || '/static/images/avater.jpeg'"
              mode="aspectFill"
            />
            <view class="ml-10rpx flex-1">
              <view class="text-#000 text-32rpx mb-10rpx font-600">{{
                userInfo?.nickname || "七尾有魔法翅膀"
              }}</view>
              <view class="flex items-center justify-between">
                <view class="text-#000 text-24rpx ml-4rpx popup-button"
                  ><uni-icons type="person"></uni-icons>
                  {{ rolesMapping[userInfo?.role] || "未知角色" }}</view
                >
                <button open-type="share" class="custom-btn">
                  <view class="flex items-center justify-between"
                    ><uni-icons type="personadd-filled"></uni-icons>
                    邀请入会</view
                  >
                </button>
              </view>
            </view>
          </view>
          <view class="flex-1 flex mt-20rpx">
            <button @click="goActivity">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/activity.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发活动</text></view
              >
            </button>
            <button @click="goActivity">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/order.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发商单</text></view
              >
            </button>
            <button @click="goInformation">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/news.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发资讯</text></view
              >
            </button>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { getNewsList, newsRemove, newsSubmit } from "@/service/news";
import { useUserStore } from "@/store";
import { storeToRefs } from "pinia";
import { superManagerPermission, managerPermission } from "@/utils";
const popupRef = ref<any>(null);

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const { safeAreaInsets } = uni.getSystemInfoSync();
const newsList = ref<any>([]);

const rolesMapping: { [key: number]: string } = {
  1: "普通",
  2: "管理员",
  3: "超级管理员",
};
const openPopup = () => {
  popupRef.value?.open();
};
const goActivity = () => {
  uni.navigateTo({
    url: "/pages-sub/publishActivity/index",
  });
};
const goInformation = () => {
  uni.navigateTo({
    url: "/pages-sub/publishInformation/index",
  });
};
// 跳转详情页
const goDetailPage = (id) => {
  uni.navigateTo({
    url: `/pages-sub/informationDetail/index?id=${id}`,
  });
};
// 取消置顶
const handleUnpin = async (id: number, st: "top" | "untop") => {
  const index = newsList.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    const res = await newsSubmit({
      id: id,
      isTop: st === "top" ? 1 : 0,
    });
    if (res.code === 200) {
      uni.showToast({
        title: st === "top" ? "已置顶" : "已取消置顶",
        icon: "success",
      });
      getList();
    }
  }
};

// 删除新闻
const handleDelete = (id: number) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条资讯吗？",
    success: async (res) => {
      if (res.confirm) {
        // 调用API接口
        await newsRemove({ ids: id.toString() });
        getList();
      }
    },
  });
};

// 上下架切换
const handleToggleStatus = async (id: number, st: "online" | "offline") => {
  const index = newsList.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    const res = await newsSubmit({
      id: id,
      status: st === "online" ? 1 : 0,
    });
    if (res.code === 200) {
      uni.showToast({
        title: st === "online" ? "已上架" : "已下架",
        icon: "success",
      });
      getList();
    }
  }
};

// 编辑新闻
const handleEdit = (newsItem: any) => {
  uni.navigateTo({
    url: `/pages-sub/publishInformation/index?id=${newsItem.id}`,
    // 可传递完整对象（注意长度限制）
    // events: {
    //   acceptData: (res: any) => {
    //     console.log('接收编辑页返回的数据', res)
    //   }
    // },
    // success: (res) => {
    //   res.eventChannel.emit('acceptData', newsItem)
    // }
  });
};
const getList = async () => {
  try {
    const showData: any = await getNewsList({
      current: "1",
      size: "1000",
    });
    newsList.value = showData.data.records;
  } catch (error) {}
};

onShow(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.news-container {
  position: relative;
  min-height: 100vh;
  padding-bottom: 30rpx;
  background: #fff;
  .ellipsis-2-lines {
    display: -webkit-box;
    -webkit-line-clamp: 2; /* 限制最多显示2行 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .news-bg {
    position: relative;
    z-index: 1;
    width: 350rpx;
    height: 350rpx;
    margin-top: -10rpx;
    margin-left: -20rpx;
    background: #e0ffb5;
    filter: blur(300rpx);
    border-radius: 350rpx;
  }
  .news-title {
    position: absolute;
    top: 40rpx;
    left: 40rpx;
    z-index: 2;
    font-size: 52rpx;
    font-weight: bold;
    color: #1a1a1a;
  }
  .news-inner {
    padding: 0 32rpx;
    margin-top: -80rpx;
    font-size: 52rpx;
    color: #1a1a1a;
  }
  .news-box {
    background: #fff;
    border: 1px solid #f1f1f1;
    border-radius: 32rpx;
  }
  .admin-actions {
    border-radius: 0 0 12rpx 12rpx; /* 圆角只作用于底部 */
    margin-top: 10rpx;
  }
}
.popup-content {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}
::v-deep .uni-popup {
  z-index: 9999 !important;
}
.custom-btn {
  background: #e0ffb5;
  border: 1px solid #1a1a1a;
  border-radius: 32rpx;
  padding: 20rpx 10rpx;
  font-size: 24rpx;
  margin-right: 0;
  line-height: 24rpx;
}
/* 通过深度选择器穿透组件样式 */
::v-deep .uni-fab__circle {
  bottom: 250rpx !important; /* 调整垂直位置 */
  z-index: 9999 !important; /* 确保层级最高 */
}
</style>
